package com.threeti.mecool.core.domain.model;

import com.threeti.mecool.core.infrastructure.persistence.CommonHintRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class Hint {
    @Autowired
    private CommonHintRepository commonHintRepository;

    public String get(HintKey key) {
        CommonHint hint = commonHintRepository.findOne(key.name());
        if (hint == null) {
            hint = insertDefault(key);
        }
        return hint.getText();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private CommonHint insertDefault(HintKey key) {
        CommonHint hint = new CommonHint(key.name(), key.getText());
        try {
            commonHintRepository.save(hint);
        } catch (Exception ignore) {
        }
        return hint;
    }
}
